﻿using Global.Impl.Client;
using Global.Interfaces.Client;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using System;
using System.IO;

namespace Client.Chat
{
    internal class Chat : IChat
    {
        private List<string> messages = new List<string>();
        public event EventHandlers.NewMessageHandler NewMessage;
        public event EventHandlers.JoinChatHandler JoinChat;
        public event EventHandlers.LeaveChatHandler LeaveChat;
        public event EventHandlers.LogHandler LogReceived;
        public event EventHandlers.FileHandler FileReceived;
        public event EventHandlers.FileNameHandler FileNameReceived;

        #region IChat Members

        public void Join(string username)
        {
            messages.Add(username + " joined (" + DateTime.Now.ToShortTimeString() + ")");
            if (JoinChat != null)
                JoinChat(username);
        }

        public void Send(string fromUsername, string msg)
        {
            messages.Add(fromUsername + "(" + DateTime.Now.ToShortTimeString() + "): " + msg);
            if (NewMessage != null)
                NewMessage(fromUsername, msg);
        }

        public void Leave(string username)
        {
            messages.Add(username + " left (" + DateTime.Now.ToShortTimeString() + ")");
            if (LeaveChat != null)
                LeaveChat(username);
        }

        public void SendLog(string log)
        {
            if (LogReceived != null)
                LogReceived(log);
        }

        public string Log
        {
            get 
            {
                StringBuilder sb = new StringBuilder();
                foreach (string entry in messages)
                {
                    sb.Append(entry);
                    sb.Append(Environment.NewLine);
                }
                return sb.ToString();
            }
        }

        public void SendFile(Stream file)
        {
            if (FileReceived != null)
                FileReceived(file);
        }

        public void SendFileName(string username, string filename)
        {
            if (FileNameReceived != null)
                FileNameReceived(username, filename);
        }

        #endregion
    }
}
